package com.renli.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.renli.exception.RenLiException;
import com.renli.model.domain.Staff;
import com.renli.model.dto.StaffDto;
import com.renli.result.R;
import com.renli.service.StaffService;
import com.renli.service.StaffWorkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;


@RestController
@RequestMapping("/staffMessage")
@Slf4j
public class StaffMessageController {
    @Autowired
    private StaffService staffService;
    @Autowired
    private StaffWorkService staffWorkService;


    //查询全部员工基本信息
    @GetMapping
    @Cacheable(value = "page", key = "'page_'+#page+'_'+#size+'_'+#name+'_'+#position")
    public R page(int page, int size, String name, String position) {
        LambdaQueryWrapper<Staff> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Staff::getName, name);
        queryWrapper.like(position != null, Staff::getPosition, position);
        queryWrapper.orderByDesc(Staff::getCreateTime);
        Page<Staff> page1 = new Page<>(page, size);
        Page<Staff> staffPage = staffService.page(page1, queryWrapper);
        return new R(1, staffPage);
    }


    //新增和修改员工id
    @CacheEvict(value = "page", allEntries = true)
    @PostMapping
    public R updateOrInsert(@RequestBody @Validated StaffDto staffDto, HttpSession session) {
        String root = (String) session.getAttribute("root");
        if (root == null) {
            throw new RenLiException("请先登陆");
        }
        return staffService.updateOrInsert(staffDto, root);
    }

    //删除员工全部信息
    @DeleteMapping("/{id}")
    @Caching(evict = {@CacheEvict(value = "page", allEntries = true),@CacheEvict(value = "salary", allEntries = true)})
    public void deleteMsg(@PathVariable Long id, HttpSession session) {
        String root = (String) session.getAttribute("root");
        if (root == null) {
            throw new RenLiException("请先登陆");
        }
        staffService.deleteStaffById(id);
    }

    //根据id查员工全部信息
    @GetMapping("/{id}")
    @Cacheable(value = "page", key = "#id")
    public R getOne(@PathVariable Long id) {
        return staffService.getOneById(id);
    }

}
